package com.example.controller;/**
 * @Author kzc
 * @Date 2023/4/22 14:53 （可以根据需要修改）
 * @作用
 */

import cn.hutool.core.codec.Base64;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.domain.GoodsOrders;
import com.example.domain.Users;
import com.example.service.IGoodsOrdersService;
import com.example.service.IUsersService;
import com.example.test.WeChatPhone;
import com.example.VO.userx;
import com.example.tools.Result;
import com.example.tools.login.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * @作用: business
 *
 * @说明:
 *
 * @author: kzc
 *
 * @日期: 2023-04-22 14:53
 **/


@RestController
@RequestMapping("/login")
public class WeChatUserLoginController {
    @Autowired
    private IUsersService usersService;

    @Autowired
    private IGoodsOrdersService goodsOrdersService;
    /**
     * 用前端请求接口获取的code换取用户手机号
     * 前端需要请求的接口：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
     *这个路径即为登录，如果手机号为空，就视为注册
     * @param
     * @return
     */
    @PostMapping("/phone")
    public Result getPhone(@RequestBody userx userx) throws Exception {
        String decrypt = decrypt(userx.getSession_key(), userx.getIv(), userx.getEncryptedData());
        Map<String, Object> map = JSONObject.parseObject(decrypt, new TypeReference<Map<String, Object>>() {});
        Users use = usersService.selectphone((String) map.get("phoneNumber"));
        if (use==null)
        {

            //添加新用户
            Users u=new Users();
            u.setUserPhone((String)map.get("phoneNumber"));
            u.setCreateTime(new Date());
            u.setIsdelete(0);
            int i = usersService.insertUsers(u);
            Users selectphone = usersService.selectphone(u.getUserPhone());

            map.put("users",selectphone);
            return Result.ok(map);
        }
        List<GoodsOrders> getid = goodsOrdersService.getid(use.getUsersId());
        use.setGs(getid);
        map.put("users",use);
        return Result.ok(map);
    }

    @PostMapping("/getidkey")
    public Result getidkey(@RequestBody WeChatPhone weChatPhone) {
//        /*设置Appid和SecretKey*/
        weChatPhone.setAppid("wxbf7c9218166b3e22");
        weChatPhone.setSecretKey("ccbd5fbe71c450ef548c1786068568c3");
//        // 1.请求微信接口服务，获取accessToken
        cn.hutool.json.JSONObject accessTokenJson = WeChatUtil.getAccessToken(weChatPhone.getAppid(), weChatPhone.getSecretKey());
        String accessToken = accessTokenJson.get("access_token", String.class);
//        // 2.请求微信接口服务，获取用户手机号信息
//        JSONObject phoneNumberJson = WeChatUtil.getPhoneNumber(weChatPhone.getCode(), accessToken);
//        WeChatPhoneInfo phoneInfo = phoneNumberJson.get("phone_info", WeChatPhoneInfo.class);
        Map<String,String> map=new HashMap<>();
        cn.hutool.json.JSONObject phoneNumberJson = WeChatUtil.getidkey(weChatPhone.getCode());
        String key =(String) phoneNumberJson.get("session_key");
        String id =(String) phoneNumberJson.get("openid");
        map.put("openid",id);
        map.put("session_key",key);
        map.put("access_token",accessToken);
        System.out.println(key);
        System.out.println(id);
        return Result.ok(map);
    }










    public static String decrypt(String keyStr, String ivStr, String encDataStr)throws Exception {

        byte[] encData = Base64.decode(encDataStr);
        byte[] iv = Base64.decode(ivStr);
        byte[] key = Base64.decode(keyStr);

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] bytes = cipher.doFinal(encData);

        return new String(cipher.doFinal(encData), "UTF-8");

    }
}
